﻿using System;
using System.Collections.Generic;
using MyBiz.Core.Products;
using System.Linq;

namespace MyBiz.Core.BuildingParts
{
    /// <summary>
    /// Реализация внутреннего хранилища магазина/склада/завода
    /// </summary>
    public class MixStorage : IStorage
    {
        private readonly Dictionary<IProductCategory, IProduct> _internalStorage = new Dictionary<IProductCategory, IProduct>();

        public double FullSize
        {
            get
            {
                return _internalStorage.Sum(product => product.Value.Count);
            }
        }

        public double GetSize(IProductCategory category)
        {
            if (!_internalStorage.ContainsKey(category))
            {
                return 0;
            }

            return _internalStorage[category].Count;
        }

        public void Add(IProduct product)
        {
            if (!_internalStorage.ContainsKey(product.Category))
            {
                _internalStorage.Add(product.Category, product);
            }
            else
            {
                var p = _internalStorage[product.Category];

                var sum = (p.Cost * p.Count + product.Cost * product.Count);
                var count = (product.Count + p.Count);

                p.Cost = count == 0 ? 0 : sum / count;

                p.Count += product.Count;
                p.Weight += p.Weight;
            }
        }

        public IProduct GetProduct(IProductCategory category, double count)
        {
            var st = _internalStorage[category];
            if (st.Count > 0)
            {
                if (st.Count >= count)
                    st.Count -= count;
                else
                {
                    count = st.Count;
                    st.Count = 0;
                }
            }
            return st.Clone(count);
        }

        public IEnumerable<IProductCategory> GetProductList()
        {
            return _internalStorage.Keys;
        }

        public string Id { get; private set; }
        public string Name { get; private set; }
    }
}